package com.android.kmlmrg.services.rest.method;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import org.json.JSONObject;

import android.app.Application;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;

import com.android.kmlmrg.R;
import com.android.kmlmrg.event.RestReportEvent;
import com.android.kmlmrg.listener.custom.RestReportListener;
import com.android.kmlmrg.model.ApiSession;
import com.android.kmlmrg.services.ServiceController;

public class Report extends AsyncTask<Void, Integer, File> {
	
	private static final  String LOG_TAG = Photo.class.getName();
	private final static String METHODE_NAME = "/report";

	private int identifiant;
	private Application vApplication;
	private int code;
	
	
	private static  ArrayList<RestReportListener> listeners = new ArrayList<RestReportListener>();


	public Report(Application pApplication ) {
	
		Log.i(LOG_TAG, "START - construct Report()");
		vApplication = pApplication;
		
		Log.i(LOG_TAG, "END - construct Report()");
	}
	
	
    protected File doInBackground(Void... sUrl) {
        try {
        	String vUrl = this.vApplication.getString(R.string.user_endpoint) + METHODE_NAME ;
        	
           	ApiSession vApiSession =  ServiceController.getInstance().getApiSession() ;
        	JSONObject vJsonObject = new JSONObject();				
			vJsonObject.put(ApiSession.WSCALLERID, vApiSession.getWsCallerId());
			vJsonObject.put(ApiSession.TIMESTAMP, vApiSession.getTimesTamp());
			vJsonObject.put(ApiSession.HASH, vApiSession.getHash());
			String message = vJsonObject.toString();
			Log.i(LOG_TAG, "Message : " + message);
        	
        
        	HttpURLConnection httpcon = (HttpURLConnection) ((new URL(vUrl).openConnection()));
      
            httpcon.setRequestProperty("Content-Type", "application/json");
            httpcon.setRequestProperty("Accept", "application/pdf");
            httpcon.setRequestMethod("POST");
           
            httpcon.setDoInput(true);
            httpcon.setDoOutput(true);
            httpcon.setFixedLengthStreamingMode(message.getBytes().length);
            httpcon.connect();
  
            
            OutputStream os = new BufferedOutputStream(httpcon.getOutputStream());
            os.write(message.getBytes());
            //clean up
            os.flush();
            
			 code = httpcon.getResponseCode();
  
            File SDCardRoot = Environment.getExternalStorageDirectory();
            //create a new file, specifying the path, and the filename
            //which we want to save the file as.
            File file = new File(SDCardRoot,"report.pdf");

            //this will be used to write the downloaded data into the file we created
            FileOutputStream fileOutput = new FileOutputStream(file);

            //this will be used in reading the data from the internet
            InputStream inputStream = httpcon.getInputStream();

            //this is the total size of the file
            int totalSize = httpcon.getContentLength();
            //variable to store total downloaded bytes
            int downloadedSize = 0;

            //create a buffer...
            byte[] buffer = new byte[1024];
            int bufferLength = 0; //used to store a temporary size of the buffer

            //now, read through the input buffer and write the contents to the file
            while ( (bufferLength = inputStream.read(buffer)) >= 0 ) {
                    //add the data in the buffer to the file in the file output stream (the file on the sd card
                    fileOutput.write(buffer, 0, bufferLength);
                    //add up the size so we know how much is downloaded
                    downloadedSize += bufferLength;
                    //this is where you would do something to report the prgress, like this maybe
                

            }
            //close the output stream when done
            fileOutput.close();   
            os.flush();
            os.close();
            inputStream.close();
           return  file;

        } catch (Exception e) {
        	e.printStackTrace();
        }
        return null;
    }


    
    

	@Override
	protected void onPostExecute(File result) {
		RestReportEvent vEvent = new RestReportEvent(this, result);
		fireEvent(vEvent);
		super.onPostExecute(result);
	}


	private void fireEvent( RestReportEvent pEvent ){		
		for(RestReportListener listener : listeners){
			listener.resultReportRequest( pEvent );
		}
	}

	public static void addListener ( RestReportListener pListener ){
		listeners.add(pListener);
	}

	public static void removeListener( RestReportListener pListener ){
		listeners.remove(pListener);
	}


}
